package com.sunlands.qdcy.tongzhuo.config;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 腾讯云对象存储
 */
@Data
@Configuration
public class COSConfig {
    @Value("${tencent.bucketName}")
    private String bucketName;
    @Value("${tencent.secretId}")
    private String secretId;
    @Value("${tencent.secretKey}")
    private String secretKey;
    @Value("${tencent.region}")
    private String region;
    @Value("${tencent.imgDomain}")
    private String imgDomain;

    @Bean
    public COSClient cosClient() {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        return new COSClient(cred, clientConfig);
    }

    /**
     * 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口 大文件上传请参照 API 文档高级 API 上传
     *
     * @param localFile

    public static String uploadfile(File localFile) throws CosClientException, CosServiceException {

    // 生成cos客户端
    COSClient cosclient = new COSClient(cred, clientConfig);
    try {
    String fileName = localFile.getName();
    String substring = fileName.substring(fileName.lastIndexOf("."));
    Random random = new Random();
    // 指定要上传到 COS 上的路径
    fileName = "images/" + random.nextInt(10000) + System.currentTimeMillis() + substring;
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, localFile);
    PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    // 关闭客户端(关闭后台线程)
    cosclient.shutdown();
    }
    return fileName;
    }



    public static void downFile() {
    // 生成cos客户端
    COSClient cosclient = new COSClient(cred, clientConfig);
    //要下载的文件路径和名称
    String key = "down/demo1.jpg";
    // 指定文件的存储路径
    File downFile = new File("src/test/resources/mydown.txt");
    // 指定要下载的文件所在的 bucket 和对象键
    GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
    ObjectMetadata downObjectMeta = cosclient.getObject(getObjectRequest, downFile);
    }



    public static void deletefile(String key) throws CosClientException, CosServiceException {
    // 生成cos客户端
    COSClient cosclient = new COSClient(cred, clientConfig);
    // 指定要删除的 bucket 和路径
    cosclient.deleteObject(bucketName, key);
    // 关闭客户端(关闭后台线程)
    cosclient.shutdown();
    } */
}
